﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MailProcessing
{
    public class CSVProcessing
    {
        public string ProcessFileAndReturnMaxNumber(string filePath) 
        {            
            int maxValue = 0;
            int localhour =  -1;
            float eCpm = -1;
            if (File.Exists(filePath))
            {
                using (StreamReader reader = new StreamReader(filePath))
                {
                    String line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        string[] data = line.Split(',');
                        int tempvalue = 0;
                        int tempLocalHour = 0;
                        float tempeCpm = -1;
                        string sTemp = string.Empty;
                        if (data.Length > 5)
                        {
                            sTemp = data[6].TrimStart().TrimEnd().Replace("\"", string.Empty);
                            if (sTemp[0].Equals('.'))
                            {
                                sTemp = string.Format("0{0}", sTemp);
                            }
                        }
                        else
                        {
                            sTemp = "0";
                        }
                       
                        if (data.Length > 1 && int.TryParse(data[2].TrimStart().TrimEnd().Replace("\"", string.Empty), out tempvalue)
                            && int.TryParse(data[0].TrimStart().TrimEnd().Replace("\"", string.Empty), out tempLocalHour)
                            && float.TryParse(sTemp, out tempeCpm) )
                        {

                            if ((tempLocalHour > localhour) ||
                                    (tempLocalHour == localhour && tempeCpm > eCpm) || 
                                    ((tempLocalHour == localhour && tempeCpm == eCpm && tempvalue > maxValue )))
                            {
                                localhour = tempLocalHour;
                                eCpm = tempeCpm;
                                maxValue = tempvalue;
                            }                           
                        }
                    }
                }
            }

            return maxValue.ToString();
        }
    }
}
